<template>
  <el-card shadow="hover" class="management-card">

    <!-- 搜索表单 -->
    <div class="aaa">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="输入用户名" clearable />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="searchForm.realName" placeholder="输入真实姓名" clearable />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="searchForm.classes" placeholder="输入班级" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="header-actions">
        <el-button class="addbutton" type="primary" size="default" @click="showAddUserDialog">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          新增用户
        </el-button>
        <el-button type="success" @click="importDialogVisible = true">
          <el-icon class="el-icon--left">
            <Upload />
          </el-icon>
          导入用户
        </el-button>
        <el-link type="primary" :underline="false" @click="downloadFile" style="margin-left: 10px;">
          下载模板
        </el-link>
      </div>

      <!-- 批量导入用户对话框 -->
      <el-dialog v-model="importDialogVisible" title="批量导入用户" width="30%">
        <el-upload class="upload-demo" drag :action="uploadUrl" :headers="headers" :on-success="handleUploadSuccess"
          :on-error="handleUploadError" :before-upload="beforeUpload" :show-file-list="false" accept=".xlsx,.xls">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              仅支持.xls/.xlsx格式文件，<el-link type="primary" @click="downloadFile">下载模板</el-link>
            </div>
          </template>
        </el-upload>
      </el-dialog>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe highlight-current-row style="width: 100%"
      header-row-class-name="custom-header">
      <el-table-column prop="avatar" label="头像" width="60" align="center">
        <template #default="{ row }">
          <el-avatar :size="30"
            :src="row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="160" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="classes" label="班级" width="120" />
      <el-table-column prop="phone" label="电话" width="180" />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="role" label="角色">
        <template #default="{ row }">
          <el-tag :type="row.role === '管理员' ? 'danger' : 'primary'" effect="dark">
            {{ row.role }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间" width="200" /> -->
      <el-table-column label="操作" width="250" align="center">
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button type="primary" size="small" plain @click="editUser(row)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button type="danger" size="small" plain @click="deleteUser(row.id)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
            <!-- 新增重置密码按钮 -->
            <el-button type="warning" size="small" plain @click="handleResetPassword(row)">
              <el-icon>
                <Refresh />
              </el-icon>
              <!-- 重置密码 -->
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分页 -->
  <div class="pagination-wrapper">
    <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
      :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange" class="mt-4" />
  </div>


  <!-- 新增用户的对话框 -->
  <el-dialog :title="isEditMode ? '编辑用户' : '新增用户'" v-model="addUserDialogVisible" width="30%"
    @closed="handleDialogClosed">
    <el-form :model="newUser" :rules="rules" ref="addUserForm" label-position="left" label-width="80px">
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload ref="uploadRef" class="avatar-uploader" :action="uploadAvatarUrl" :show-file-list="false"
          :auto-upload="false" :on-change="handleFileChange" :before-upload="beforeAvatarUpload">
          <img v-if="newUser.avatar" :src="newUser.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="newUser.username" class="form-input"></el-input>
      </el-form-item>
      <!-- <el-form-item label="密码" prop="password" v-if="!isEditMode">
        <el-input type="password" v-model="newUser.password" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-else>
        <el-input type="password" v-model="newUser.password" placeholder="留空则不修改密码" class="form-input"></el-input>
      </el-form-item> -->
      <el-form-item label="角色" prop="role">
        <el-select v-model="newUser.role" placeholder="请选择角色" class="form-input">
          <el-option label="管理员" value="管理员"></el-option>
          <el-option label="学生" value="学生"></el-option>
          <el-option label="班主任" value="班主任"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="newUser.realName" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="班级" prop="classes">
        <el-input v-model="newUser.classes" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="newUser.phone" class="form-input"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="newUser.email" class="form-input"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">{{ isEditMode ? '更新' : '确定' }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { Plus, Edit, Delete, Refresh, Upload } from '@element-plus/icons-vue'
import { get } from '@/request/request.js';
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios';

// 导入上传组件
// 新增导入相关状态
const importDialogVisible = ref(false)
const uploadUrl = ref(`http://localhost:5000/api/importUsers`)
// 下载模板
const downloadFile = () => {
  const link = document.createElement('a');
  link.href =
    'https://jobsystem.oss-cn-beijing.aliyuncs.com/%E7%94%A8%E6%88%B7%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
  link.click();
  link.remove(); // 清理临时元素
};

// 文件上传前校验
const beforeUpload = (file) => {
  const isExcel = file.type.includes('excel') ||
    file.name.endsWith('.xlsx') ||
    file.name.endsWith('.xls')
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }
  return true
}

// 上传成功处理
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success(`导入成功`)
    fetchData(currentPage.value)
    importDialogVisible.value = false
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

// 上传错误处理
const handleUploadError = (error) => {
  ElMessage.error(`文件上传失败：${error.message}`)
}

// 新增搜索表单数据
const searchForm = ref({
  username: '',
  realName: '',
  classes: ''
})

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const uploadRef = ref()
const avatarFile = ref(null)

// const pageSize = 10
let pageSize = ref(10)
const addUserDialogVisible = ref(false)
// 新增状态变量
const isEditMode = ref(false)
const currentUserId = ref(null)
const newUser = ref({
  username: '',
  password: '123456',
  role: '',
  realName: '',
  classes: '',
  phone: '',
  email: '',
  avatar: '',
})

// 调整验证规则（使用计算属性）
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: isEditMode.value ? [] : [ // 编辑模式不需要密码必填
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  classes: [{ required: true, message: '请输入班级', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  avatar: [{ required: !isEditMode.value, message: '请上传头像', trigger: 'change' }]
}

// 获取用户数据
const fetchData = async (page = 1) => {
  try {
    const params = {
      ...searchForm.value,
      page: page,
      pageSize: pageSize.value
    }
    const response = await get('/api/users', params)
    tableData.value = response.data.list
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('用户列表获取失败')
    console.error('Error fetching users:', error)
  }
}

// 搜索处理函数
const handleSearch = () => {
  fetchData()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    username: '',
    realName: '',
    classes: ''
  }
  handleSearch()
}

// 显示新增用户对话框
const showAddUserDialog = () => {
  addUserDialogVisible.value = true
}

// 新增重置密码处理函数
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要将密码重置吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    currentUserId.value = row.id
    newUser.value = {
      ...row
    }
    const userData = { ...newUser.value }
    userData.password = '123456'
    // 调用重置密码接口
    await get('/api/updateUser', userData)
    ElMessage.success('密码重置成功')
    fetchData(currentPage.value)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
      console.error('Error resetting password:', error)
    }
  }
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchData(page)
}

// 每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchData(currentPage.value)
}

// 删除用户
const deleteUser = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await get(`/api/deleteUser/${id}`)
    ElMessage.success('删除成功')
    fetchData(currentPage.value)
  } catch (error) {
    ElMessage.error('删除失败')
    console.error('Error deleting user:', error)
  }
}


// 文件选择处理
const handleFileChange = (file) => {
  avatarFile.value = file.raw
  // 生成本地预览URL（不实际上传）
  newUser.value.avatar = URL.createObjectURL(file.raw)
}

// 统一提交处理
// 修改提交函数
const handleSubmit = async () => {
  try {
    // 1. 上传头像
    if (avatarFile.value) {
      const formData = new FormData()
      formData.append('file', avatarFile.value) // 字段名必须和后端一致
      // 重要：不要手动设置Content-Type头，让浏览器自动添加boundary
      const uploadRes = await axios.post(uploadAvatarUrl.value, formData)
      if (uploadRes.data.code !== 200) {
        throw new Error(uploadRes.data.message || '头像上传失败')
      }
      newUser.value.avatar = uploadRes.data.data // 存储返回的URL
    }

    // 3. 提交用户数据
    const userData = { ...newUser.value }
    if (isEditMode.value) {
      userData.id = currentUserId.value
      await get('/api/updateUser', userData)
      ElMessage.success('用户更新成功')
    } else {
      await get('/api/addUser', userData)
      ElMessage.success('用户添加成功')
    }

    addUserDialogVisible.value = false
    fetchData(currentPage.value)
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

// 新增表单引用
const addUserForm = ref(null)
// 处理对话框关闭事件
// 修改对话框关闭处理
const handleDialogClosed = () => {
  if (addUserForm.value) {
    addUserForm.value.resetFields()
  }
  isEditMode.value = false
  currentUserId.value = null
  // 重置表单数据
  newUser.value = {
    username: '',
    password: '',
    role: '',
    realName: '',
    classes: '',
    phone: '',
    email: ''
  }
}

const editUser = (user) => {
  // 编辑用户逻辑
  isEditMode.value = true
  currentUserId.value = user.id
  // 使用扩展运算符复制用户数据，避免引用
  newUser.value = {
    ...user,
    password: '', // 清空密码字段
    avatar: user.avatar || ''
  }
  addUserDialogVisible.value = true
}

// 头像上传相关
const uploadAvatarUrl = ref('http://localhost:5000/api/uploadAvatar')


// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

onMounted(() => {
  fetchData(1)
})
</script>

<style lang="scss" scoped>
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
  }
}

// 表格中的头像样式
:deep(.el-table__cell) .el-avatar {
  margin: 0 auto;
}

/* 新增按钮间距样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
  /* 调整按钮间距 */
}

.addbutton {
  margin-bottom: 5px;
  float: right;
}

.search-form {
  float: left;
  // margin-bottom: 20px;
  width: 80%;

  .el-form-item {
    margin-right: 20px;

    &:last-child {
      margin-right: 0;
    }
  }

  .el-input {
    width: 180px;
  }
}

.management-card {
  height: 100%;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  :deep(.el-card__header) {
    border-bottom: 1px solid #ebeef5;
    background: linear-gradient(135deg, #f8f9fc, #ffffff);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;

    .card-title {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.custom-header {
  th {
    background-color: #f5f7fa !important;
    color: #606266;
    font-weight: 600;
  }
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.pagination-wrapper {
  background-color: #ffffff;
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;

  .el-table__cell {
    transition: background-color 0.3s ease;
  }
}

.el-tag {
  border-radius: 4px;
  font-weight: 500;
}

// 添加对话框布局样式
:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;

  .el-form-item {
    margin-bottom: 18px;

    &__label {
      text-align: left;
      padding-right: 12px;
    }
  }

  .form-input {
    width: 100%;

    :deep(.el-input__wrapper) {
      width: 100%;
    }
  }

  .el-select {
    width: 100%;
  }
}

.dialog-footer {
  padding: 0 20px 20px;
}
</style>
